package com.wskh.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wskh.edu.entity.Subject;
import com.wskh.edu.entity.excel.SubjectData;
import com.wskh.edu.service.SubjectService;
import com.wskh.serviceBase.exception.XbException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//创建读取excel监听器
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //创建list集合封装最终的数据
    List<SubjectData> list = new ArrayList<SubjectData>();

    //一行一行去读取excle内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new XbException(200, "上传的分类文件数据为空");
        } else {
            //添加一级分类
            Subject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
            if (existOneSubject == null) {
                // 数据库中无相同的一级分类,可以进行添加
                existOneSubject = new Subject();
                existOneSubject.setTitle(subjectData.getOneSubjectName());
                existOneSubject.setParentId("0");
                subjectService.save(existOneSubject);
            }

            //获取一级分类id值
            String pid = existOneSubject.getId();
            //添加二级分类
            Subject existTwoSubject =
                    this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
            if (existTwoSubject == null) {
                existTwoSubject = new Subject();
                existTwoSubject.setTitle(subjectData.getTwoSubjectName());
                existTwoSubject.setParentId(pid);
                subjectService.save(existTwoSubject);
            }

        }
    }

    //判断一级分类是否重复
    private Subject existOneSubject(SubjectService subjectService, String
            name) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    //判断二级分类是否重复
    private Subject existTwoSubject(SubjectService subjectService, String
            name, String pid) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    //读取excel表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext
            context) {
        System.out.println("表头信息：" + headMap);
    }

    //读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
